import logging
from logging.handlers import RotatingFileHandler

class Logger:
    def __init__(self, name, log_file='log', level=logging.INFO):
        # 创建一个 logger 对象
        self.logger = logging.getLogger(name)
        self.logger.setLevel(level)  # 设置日志级别

        # 创建一个 handler，用于写入日志文件
        file_handler = RotatingFileHandler(log_file, maxBytes=1024*1024*5, backupCount=5)
        file_handler.setLevel(level)

        # 创建一个 handler，用于输出到控制台
        console_handler = logging.StreamHandler()
        console_handler.setLevel(level)

        # 定义 handler 的输出格式
        formatter = logging.Formatter('%(asctime)s - %(module)s - %(name)s - %(funcName)s- -%(lineno)d - %(levelname)s - %(message)s')
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)

        # 给 logger 添加 handler
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)

    def get_logger(self):
        return self.logger

# 使用示例
if __name__ == "__main__":
    # 初始化 Logger 类
    my_logger = Logger('MyLogger').get_logger()

    # 记录不同级别的日志
    my_logger.debug('This is a debug message')
    my_logger.info('This is an info message')
    my_logger.warning('This is a warning message')
    my_logger.error('This is an error message')
    my_logger.critical('This is a critical message')